/**
 * Created by zhangyy on 2018.05.17.
 * 角色与权限管理js
 */
(function() {
	var app = angular.module('roleAndAuthorityManagementApp', [ 'ui.bootstrap' ]);
	app.controller(
					'roleAndAuthorityManagementController',
					function($http,$scope, $log, $uibModal,$filter) {
						$scope.insertComponent = {};
						$scope.deleteComponent = {};
						var controller = this;
						controller.parmater = {};
						this.dataList = [];
						this.queryCondition = {
							"userNo" : "",
							"userName" : "",
							"belong_to_reglon" : "",
							"belong_to_department" : "",
							"date" : "",
							"page" : 1,
							"size" : 10,
						};
						this.paginationInfo = {
							"maxSize" : 5,
							"totalPages" : 0,
							"totalElements" : 0
						};
						

						$scope.clickEvent = function() {
							controller.queryCondition.page = controller.queryCondition.forwordPage;
							loadData();
						}

						// 跳转页数，回车事件
						$scope.enterEvent = function(e) {
							var keycode = window.event ? e.keyCode : e.which;
							if (keycode == 13) {
								$scope.clickEvent();
							}
						}

						this.pageChanged = function() {
							loadData();
						}
		


						this.changeDate = function() {
						}
						// 完成全选全部选事件
						$("#check_all").click(
								function() {
									$(".check_item").prop("checked",
											$(this).prop("checked"));
								});
						// 选中单个元素，如果单个元素选择满了，那么第一个主元素也被选中
						$(document)
								.on(
										"click",
										".check_item",
										function() {
											if ($(".check_item:checked").length == $(".check_item").length) {
												$("#check_all").prop("checked",
														true);
											}
											if ($(".check_item:checked").length == 0) {
												$("#check_all").prop("checked",
														false);
											}
										});
	
						// 搜索事件
						this.search = function() {
							loadData();
						}

						// 重置事件
						this.reset = function() {
							controller.queryCondition.roleName="";
							loadData();
						}

						// 删除角色
						this.delRoles = function() {
							var basePath = $scope.getAppBasePath();
							var empId = "";
							var empNo = "";
							$.each($(".check_item:checked"), function() {
								empId += $(this).parents("tr").find("td:eq(1)")
										.text()
										+ ",";
								empNo += $(this).parents("tr").find("td:eq(2)")
										.text()
										+ ",";
							})
							// 如果没有选中的话
							if (empId == "" || empNo == "") {
								alert("请选择要删除的角色");
								return;
							} else {
								deleteComponent = {
									"roleName" : null
								};
								deleteComponent.roleName = empNo;
								if (confirm("确认删除角色：["
										+ deleteComponent.roleName + "]吗?")) {
									// 删除后台调用
									$.ajax({
												type : "POST",
												url : basePath+ "/data/deleteRoles",
												dataType : "json",
												data : {"ids":empId},
												success : function(data) {
													alert("删除成功");
													loadData();
												}
											});

								}
							}
						}
						// 创建角色点击弹窗事件
						this.createRole = function() {
							$scope.insertComponent = {};
							var modalInstanceAdd = $uibModal
									.open({
										backdrop : 'static',
										keyboard : false,
										scope : $scope,
										// animation :
										// $scope.animationsEnabled,// 打开时的动画开关
										templateUrl : 'js/controller/system.management/creatRole.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										controller : 'createRoleController',// 这是模态框的控制器,是用来控制模态框的
										ariaLabelledBy : 'modal-title',
										ariaDescribedBy : 'modal-body',
									// size : "lg",// 模态框的大小尺寸
									});
							
							modalInstanceAdd.opened.then(function(){//模态窗口打开之后执行的函数  
								//加载menu树结构数据
								getMenuData(1,"1");
			            
							}); 
			
							modalInstanceAdd.result.then(function(result) {
								loadData();
							});
						}

						
						// 更改角色权限   
						this.changeRolePermissions = function(data) {
							$scope.updateComponent = angular.copy(data) || {};
							$scope.updateComponent.roleName =data.name;
							$scope.updateComponent.roelDescription =data.description;
							
							var modalInstanceUpdate = $uibModal
									.open({
										backdrop : 'static',
										keyboard : false,
										scope : $scope,
										// animation :
										// $scope.animationsEnabled,// 打开时的动画开关
										templateUrl : 'js/controller/system.management/changeRolePermissions.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										controller : 'changeRolePermissionsController',// 这是模态框的控制器,是用来控制模态框的
										ariaLabelledBy : 'modal-title',
										ariaDescribedBy : 'modal-body',
									// size : "lg",// 模态框的大小尺寸
									});

							modalInstanceUpdate.opened.then(function(){//模态窗口打开之后执行的函数  
								//加载menu树结构数据
								getMenuData(2,data);
			            
				         }); 
						

							modalInstanceUpdate.result.then(function(result) {
								loadData();
							});

						}
						// 程序初期化
						this.init = function() {
							//加载页面列表展示数据
							loadData();

						}

						this.init();
						// 加载数据
						function loadData() {
	
							// 参数获取
							controller.parmater.roleName = controller.queryCondition.roleName || "";

							var basePath = $scope.getAppBasePath();

							controller.parmater.page = controller.queryCondition.page;
							controller.parmater.size = controller.queryCondition.size;

							// 后台调用
			
							$.ajax({
								type : "POST",
								url : basePath + "/data/getRoles",
								dataType : "json",
								data :  {"roleName":controller.parmater.roleName, "page":controller.parmater.page, "size": controller.parmater.size},
								success : function(data) {
									var jsonResult = angular.fromJson(data);
									controller.dataList = jsonResult.data;
									controller.paginationInfo.totalPages = jsonResult.totalPages;
									controller.paginationInfo.totalElements = jsonResult.totalElements;
									//手动刷新
									$scope.$apply();  
								}
							 });
						}
						
						//加载menu树结构数据
			
						function getMenuData(type,params){
							var basePath = $scope.getAppBasePath();
							var zTreeObj;
							$.ajax({
								type : "POST",
								url : basePath + "/data/getMenus",
								dataType : "json",
						
								success : function(data) {
									var resultMenusArrary = angular.fromJson(data);
									// zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
									var setting = {
									   
										check: {
											enable: true,
											chkStyle: "checkbox",
											//chkboxType: { "Y": "p", "N": "s" }
										},
									   callback : { //返回函数; 根据需求选择合适的监听事件  //以下事件默认权威null 事件例子参见第83行
						

									   }
									};

									zTreeObj = $.fn.zTree.init($("#menuJurisdiction"), setting, resultMenusArrary);
									if(type==2){
										//选中已有menu权限
										var zTree = $.fn.zTree.getZTreeObj("menuJurisdiction");

										var node ;
										var result=params.menuIds.split(",");
										for(var i=0;i<result.length;i++){
											if(result[i] == null || result[i] ==""){
												continue;
											}
											node=zTree.getNodeByParam("id",parseInt(result[i]));
											node.checked = true;
											zTree.updateNode(node);//注：设置checked属性之后，一定要更新该节点，否则会出现只有鼠标滑过的时候节点才被选中的情况
										}
									}
								}
							});
						}

					})
			//创建角色数据库操作		
			.controller(
					'createRoleController',
					function($scope, $uibModalInstance, $http, $log,$filter) {
						$scope.save = function() {
							//提交前验证
							if($scope.$parent.insertComponent.roleName == null || $scope.$parent.insertComponent.roleName ==''){
								alert("角色名称还没填写奥！");
								return;
							}
							
							if($scope.$parent.insertComponent.roelDescription == null || $scope.$parent.insertComponent.roelDescription ==''){
								alert("简单介绍下当前角色！");
								return;
							}
							
							//获取角色menu权限
				            var treeObj=$.fn.zTree.getZTreeObj("menuJurisdiction"),
				            nodes=treeObj.getCheckedNodes(true),
				            ids="";
							if(nodes.length==0){
								alert("请选择MENU后保存！");
								return;
							}
				            for(var i=0;i<nodes.length;i++){
				            	ids+=nodes[i].id + ",";//获取选中节点的值
				            }
				            

							
							var basePath = $scope.getAppBasePath();
							
							var createTime = new Date();
							var updateTime = new Date();
							var state =1;  //暂时给的死数据后期根据需求修改
							var code = 0;  //不明确字段暂时写死0 
							var name = $scope.$parent.insertComponent.roleName||"";
							var description = $scope.$parent.insertComponent.roelDescription||"";


							// 后台调用
							$.ajax({
								type : "POST",
								url : basePath + "/data/createRole",
								dataType : "json",
								data :{
									"createTime":createTime ,
									"updateTime":updateTime ,
									"state":state ,
									"code":code ,
									"name":name ,
									"description":description ,
									"mIds":ids 
								} ,
								success : function(data) {
									$uibModalInstance.close();
									
									alert("创建成功");
								}
							});
							
						};
						$scope.cancel = function() {
							// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
							$uibModalInstance.dismiss('cancel');
						};
					})
					//更改权限数据库操作
			.controller(
					'changeRolePermissionsController',
					function($scope, $uibModalInstance, $http, $log,$filter) {
						$scope.save = function() {
							//提交前验证
							if($scope.updateComponent.roleName == null || $scope.updateComponent.roleName ==''){
								alert("角色名称还没填写奥！");
								return;
							}
							
							if($scope.updateComponent.description == null ||$scope.updateComponent.description ==''){
								alert("简单介绍下当前角色！");
								return;
							}
							
							//获取角色menu权限
				            var treeObj=$.fn.zTree.getZTreeObj("menuJurisdiction"),
				            nodes=treeObj.getCheckedNodes(true),
				            menuIds="";
							if(nodes.length==0){
								alert("请选择MENU后保存！");
								return;
							}
				            for(var i=0;i<nodes.length;i++){
				            	menuIds+=nodes[i].id + ",";//获取选中节点的值
				            }
							
							
							
							
							var basePath = $scope.getAppBasePath();

							// UPDATE值获取
							var id = $scope.updateComponent.id;
							var name = $scope.updateComponent.roleName;
							var description = $scope.updateComponent.description;
							var createTime =new Date($scope.updateComponent.createTime);
							var updateTime = new Date();
							var state = $scope.updateComponent.state;
							var code = $scope.updateComponent.code;


							// 后台调用
							$.ajax({
								type : "POST",
								url : basePath + "/data/changeRolePermissions",
								dataType : "json",
								data :{
									"id":id ,
									"createTime":createTime ,
									"updateTime":updateTime ,
									"state":state ,
									"code":code ,
									"name":name ,
									"description":description,
									"mIds":menuIds 
								} ,
								success : function(data) {
									alert("更新成功");
								}
							});
							$uibModalInstance.close();
						};
						$scope.cancel = function() {
							// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
							$uibModalInstance.dismiss('cancel');
						};
					});
})();